package com.jeff.practice;

import java.util.HashMap;
import java.util.Map;

public class Test6 {
    public static boolean isIsomorphic(String s, String t) {
        if (s == null || t == null || s.length() != t.length()) {
            return false;
        }

        Map<Character, Character> mapSToT = new HashMap<>();
        Map<Character, Character> mapTToS = new HashMap<>();

        for (int i = 0; i < s.length(); i++) {
            char charS = s.charAt(i);
            char charT = t.charAt(i);

            // 检查s到t的映射
            if (mapSToT.containsKey(charS)) {
                if (mapSToT.get(charS) != charT) {
                    return false;
                }
            } else {
                mapSToT.put(charS, charT);
            }

            // 检查t到s的映射
            if (mapTToS.containsKey(charT)) {
                if (mapTToS.get(charT) != charS) {
                    return false;
                }
            } else {
                mapTToS.put(charT, charS);
            }
        }

        return true;
    }

    public static void main(String[] args) {
        String s = "egg";
        String t = "add";
        System.out.println(isIsomorphic(s, t));  // 输出: true

        s = "foo";
        t = "bar";
        System.out.println(isIsomorphic(s, t));  // 输出: false
    }
}
